import { Editor, EditorProps } from "../editor";
import { State as ControlState, default as SingleColunmProductsControl } from "./control";
import { ShoppingService } from "../../admin/services/shopping";
import { ProductSelectDialog } from "../../admin/controls/productSelectDialog";
import ReactDOM = require("react-dom");
import { ImageService } from "maishu-services-sdk";
import React = require("react");
import * as ui from "maishu-ui-toolkit";

export interface State extends Partial<ControlState> {
}

export default class SingleColunmProductsEditor extends Editor<EditorProps, State>{
    private shoppingService: ShoppingService;
    productThumbers: HTMLElement;
    imageService: ImageService;

    constructor(props) {
        super(props)

        this.loadEditorCSS();
        this.shoppingService = this.props.elementPage.createService(ShoppingService);
        this.imageService = this.props.elementPage.createService(ImageService);
    }

    setRadioElement(e: HTMLInputElement, member: Extract<keyof State, string>) {
        if (!e || e.onchange) return;
        e.checked = (this.state[member] || '').toString() == e.value;
        e.onchange = () => {
            let obj = {};
            obj[member] = e.value;
            this.setState(obj);
        }
    }

    setProductCategoryInput(e: HTMLSelectElement) {
        if (!e || e.onchange) return;

        e.onchange = () => {
            this.state.categoryId = e.value;
            this.setState(this.state);
        }
        this.shoppingService.categories().then(categories => {
            for (let i = 0; i < categories.length; i++) {
                var option = document.createElement('option');
                option.value = categories[i].Id;
                option.text = categories[i].Name;
                e.appendChild(option);
            }
            e.value = this.state.categoryId || '';
        });
    }

    setProductsCountInput(e: HTMLSelectElement) {
        if (!e || e.onchange) return;

        for (let i = 1; i < 9; i++) {
            var option = document.createElement('option');
            option.value = i as any;
            option.text = i as any;
            e.appendChild(option);
        }
        e.value = `${this.state.productsCount}`;
        e.onchange = () => {
            this.state.productsCount = Number.parseInt(e.value);
            this.setState(this.state);
        }
        // e.options[0].selected = true;
    }

    setProductDelete(e: HTMLButtonElement, productId: string) {
        if (!e || e.onclick)
            return;

        e.onclick = () => {
            this.state.productIds = this.state.productIds.filter(o => o != productId);
            this.setState(this.state);
        }
    }

    setProductAdd(e: HTMLElement) {
        if (!e || e.onclick)
            return;

        e.onclick = () => {
            ProductSelectDialog.show((products) => this.productSelected(products));
        }
    }


    productSelected(products: Product[]): Promise<any> {
        let productIds = this.state.productIds || [];

        // 排除已存在的 product id
        let newProducts = products.map(o => o.Id).filter(o => productIds.indexOf(o) < 0)

        productIds.push(...newProducts);

        this.state.productIds = productIds;
        this.setState(this.state);
        return Promise.resolve();
    }

    async renderProducts(container: HTMLElement, productIds: string[]) {
        if (!container) return;

        var products = (productIds || []).length == 0 ? [] : await this.shoppingService.productsByIds(productIds);
        var reactElement =
            <ul className="selected-products"
                ref={(e: HTMLElement) => this.productThumbers = e || this.productThumbers}>
                {products.map(o =>
                    <li key={o.Id} product-id={o.Id} title="拖动图标可以对商品进行排序">
                        <img src={this.imageService.imageSource(o.ImagePath, 100)}
                            ref={(e: HTMLImageElement) => e ? ui.renderImage(e) : null} />
                        <div className="delete">
                            <button type="button" className="btn-link"
                                ref={(e: HTMLButtonElement) => this.setProductDelete(e, o.Id)}>
                                删除
                            </button>
                        </div>
                    </li>
                )}
                <li className="product-add">
                    <i className="icon-plus icon-4x" ref={(e: HTMLElement) => this.setProductAdd(e)} />
                </li>
            </ul>;

        ReactDOM.render(reactElement, container, () => {
            $(this.productThumbers).sortable({
                update: () => {
                    let productIds: string[] = [];
                    this.productThumbers.querySelectorAll("[product-id]").forEach(o => {
                        productIds.push(o.getAttribute('product-id'));
                    });

                    let ctrl = (this.props.control as SingleColunmProductsControl);
                    this.state.productIds = productIds;
                    ctrl.state.productIds = productIds;
                    this.setState(this.state);
                    ctrl.setState(ctrl.state);
                },
                items: 'li[product-id]'
            });
        });
    }

    render() {
        let { productSourceType, productIds } = this.state;
        return <form className="product-list-editor">
            <div className="form-group">
                <label className="pull-left">数据来源</label>
                <span>
                    <input name="sourceType" type="radio" value="category"
                        ref={(e: HTMLInputElement) => this.setRadioElement(e, 'productSourceType')} />
                    分类
                </span>
                <span>
                    <input name="sourceType" type="radio" value="custom"
                        ref={(e: HTMLInputElement) => this.setRadioElement(e, 'productSourceType')} />
                    手动添加
                </span>
            </div>
            <div key={20} className="form-group">
                <label className="pull-left">图片大小</label>
                <span>
                    <input name="imageSize" type="radio" value="small"
                        ref={(e: HTMLInputElement) => this.setRadioElement(e, 'imageSize')} />
                    小
                </span>
                <span>
                    <input name="imageSize" type="radio" value="medium"
                        ref={(e: HTMLInputElement) => this.setRadioElement(e, 'imageSize')} />
                    中
                </span>
                <span>
                    <input name="imageSize" type="radio" value="large"
                        ref={(e: HTMLInputElement) => this.setRadioElement(e, 'imageSize')} />
                    大
                </span>
            </div>
            <div key={10} className="form-group">
                <label className="pull-left">商品名称</label>
                <span>
                    <input name="productNameLines" type="radio" value="singleLine"
                        ref={(e: HTMLInputElement) => this.setRadioElement(e, 'productNameLines')} />
                    单行文字
                            </span>
                <span>
                    <input name="productNameLines" type="radio" value="doubleLine"
                        ref={(e: HTMLInputElement) => this.setRadioElement(e, 'productNameLines')} />
                    双行文字
                </span>
            </div>
            <div className="form-group clearfix">
                <label className="pull-left">商品数量</label>
                <div>
                    <select className="form-control"
                        ref={(e: HTMLSelectElement) => this.setProductsCountInput(e)} />
                </div>
            </div>
            <div className="form-group">
                <label className="pull-left">商品类别</label>
                <div>
                    <select className="form-control"
                        ref={(e: HTMLSelectElement) => this.setProductCategoryInput(e)} >
                        <option value="">所有商品</option>
                    </select>
                </div>
            </div>

            <div className="form-group clearfix" style={{ display: productSourceType == 'custom' ? 'block' : 'none' }}>
                <label className="pull-left">选取商品</label>
                <div style={{ width: 'calc(100% - 100px)', marginLeft: 100 }}
                    ref={(e: HTMLElement) => this.renderProducts(e, productIds)}></div>
            </div>
        </form>
    }

}